<template>
  <view>
    <view 
      v-if="isVisible" 
      class="desktop-pet"
      :class="{
        'pet-mobile': isMobile,
        'pet-pc': !isMobile,
        'pet-following': isFollowing,
        'pet-interacting': isInteracting
      }"
      :style="petPosition"
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
      @touchcancel="handleTouchCancel"
      @click="handlePCClick"
    >
      <!-- 宠物主体 - Canvas版本优先 -->
      <PetCanvas 
        v-if="useCanvas && !useFallback"
        :pet-data="petData"
        :current-animation="currentAnimation"
        :is-dragging="isDragging"
        @canvas-error="handleCanvasError"
        @canvas-ready="handleCanvasReady"
      />
      
      <!-- 降级到CSS版本 -->
      <PetAvatar 
        v-else
        :pet-data="petData"
        :current-animation="currentAnimation"
        :is-dragging="isDragging"
      />
      
      <!-- PC端信息面板 -->
      <PetInfoPanel 
        v-if="!isMobile"
        :visible="showInfoPanel"
        :pet-data="petData"
        @close="closeInfoPanel"
        @feed="feedPet"
        @play="playWithPet"
        @rest="restPet"
      />
    </view>

    <!-- 交互气泡 - 独立于宠物容器，跟随宠物位置 -->
    <PetBubble 
      v-if="isVisible"
      :show-bubble="showBubble"
      :bubble-text="bubbleText"
      :bubble-type="bubbleType"
      :pet-position="petPosition"
    />

    <!-- 移动端自定义菜单 -->
    <PetCustomMenu 
      v-if="isMobile"
      :visible="showCustomMenu"
      :menu-position="menuPosition"
      :is-listening="isListening"
      @select="selectMenuItem"
      @close="closeCustomMenu"
    />
    
    <!-- 移动端信息面板 -->
    <PetMobileInfoPanel 
      v-if="isMobile"
      :visible="showMobileInfoPanel"
      :pet-data="petData"
      @close="closeMobileInfoPanel"
      @feed="feedPet"
      @play="playWithPet"
      @rest="restPet"
    />
  </view>
</template>

<script>
import speechRecognitionManager from '@/utils/speech-recognition.js'
import PetAvatar from './PetAvatar.vue'
import PetCanvas from './PetCanvas.vue'
import PetBubble from './PetBubble.vue'
import PetInfoPanel from './PetInfoPanel.vue'
import PetCustomMenu from './PetCustomMenu.vue'
import PetMobileInfoPanel from './PetMobileInfoPanel.vue'

export default {
  name: 'DesktopPet',
  components: {
    PetAvatar,
    PetCanvas,
    PetBubble,
    PetInfoPanel,
    PetCustomMenu,
    PetMobileInfoPanel
  },
  props: {
    // 宠物数据
    petData: {
      type: Object,
      required: true
    },
    // 是否可见
    visible: {
      type: Boolean,
      default: true
    },
    // 平台类型
    platform: {
      type: String,
      default: 'auto' // auto, mobile, pc
    }
  },
  
  data() {
    return {
      // 显示状态
      isVisible: true,
      showInfoPanel: false,
      showBubble: false,
      bubbleText: '',
      bubbleType: 'normal',
      
      // 交互状态
      isFollowing: false,
      isInteracting: false,
      currentAnimation: 'idle',
      
      // 位置相关
      position: { x: 50, y: 50 }, // 百分比位置
      isDragging: false,
      dragStartPos: null,
      systemInfo: null,
      
      // 定时器
      bubbleTimer: null,
      animationTimer: null,
      statusUpdateTimer: null,
      
      // 设备检测
      isMobile: false,
      
      // 识别相关
      recognitionActive: false,
      speechRecognition: null,
      isListening: false,
      
      // 防重复调用
      isActionSheetShowing: false,
      
      // 自定义菜单
      showCustomMenu: false,
      
      // 移动端信息面板
      showMobileInfoPanel: false,
      
      // Canvas相关
      useCanvas: true,  // 默认使用Canvas
      useFallback: false  // 是否降级到CSS版本
    }
  },
  
  computed: {
    // 菜单位置计算
    menuPosition() {
      if (!this.systemInfo) return {}
      
      const screenWidth = this.systemInfo.windowWidth
      const screenHeight = this.systemInfo.windowHeight
      const petSize = this.isMobile ? 100 : 80 // 宠物大小（像素）
      
      // 计算宠物在屏幕上的实际位置
      const petX = (this.position.x / 100) * screenWidth
      const petY = (this.position.y / 100) * screenHeight
      
      // 菜单大小（像素，280rpx ≈ 140px）
      const menuWidth = 140
      const menuHeight = 400 // 5个选项
      
      // 计算菜单位置，避免超出屏幕
      let left = petX + petSize + 15 // 宠物右侧，增加间距
      let top = petY - menuHeight / 2 + petSize / 2 // 垂直居中对齐宠物中心
      
      // 如果右侧空间不够，显示在左侧
      if (left + menuWidth > screenWidth - 20) {
        left = petX - menuWidth - 15
      }
      
      // 如果左侧也不够，居中显示
      if (left < 20) {
        left = screenWidth / 2 - menuWidth / 2
        top = petY + petSize + 15 // 显示在宠物下方
      }
      
      // 如果上方空间不够，调整到屏幕内
      if (top < 20) {
        top = 20
      }
      
      // 如果下方空间不够，调整到屏幕内
      if (top + menuHeight > screenHeight - 20) {
        top = screenHeight - menuHeight - 20
      }
      
      return {
        left: left + 'px',
        top: top + 'px'
      }
    },
    
    petPosition() {
      return {
        left: this.position.x + '%',
        top: this.position.y + '%',
        transform: this.isDragging ? 'scale(1.1)' : 'scale(1)',
        transition: this.isDragging ? 'none' : 'all 0.3s ease'
      }
    }
  },
  
  mounted() {
    this.checkCanvasSupport()
    this.initPet()
    this.detectPlatform()
    this.startStatusUpdate()
    this.setupSpeechRecognition()
    
  },
  
  beforeDestroy() {
    this.cleanup()
  },
  
  watch: {
    visible(newVal) {
      this.isVisible = newVal
    },
    
    petData: {
      handler(newData) {
        this.checkPetStatus(newData)
      },
      deep: true
    }
  },
  
  methods: {
    // 初始化宠物
    initPet() {
      this.isVisible = this.visible
      this.loadPetPosition()
      this.startRandomAnimations()
      this.showWelcomeMessage()
    },
    
    // 检测平台
    detectPlatform() {
      this.systemInfo = uni.getSystemInfoSync()
      this.isMobile = this.systemInfo.platform !== 'windows' && this.systemInfo.platform !== 'mac'
      
      console.log('Platform detected:', this.systemInfo.platform, 'isMobile:', this.isMobile)
      
      // 根据平台调整初始位置
      if (this.isMobile) {
        this.position = { x: 80, y: 70 } // 移动端右下角
      } else {
        this.position = { x: 85, y: 60 } // PC端右下角
      }
    },
    
    // 加载宠物位置
    loadPetPosition() {
      try {
        const savedPos = uni.getStorageSync('desktop_pet_position')
        if (savedPos) {
          this.position = savedPos
        }
      } catch (error) {
        console.log('加载宠物位置失败:', error)
      }
    },
    
    // 保存宠物位置
    savePetPosition() {
      try {
        uni.setStorageSync('desktop_pet_position', this.position)
      } catch (error) {
        console.log('保存宠物位置失败:', error)
      }
    },
    
    // 触摸开始
    handleTouchStart(e) {
      console.log('Touch start, isMobile:', this.isMobile)
      
      if (this.isMobile && e.touches && e.touches.length > 0) {
        const touch = e.touches[0]
        this.dragStartPos = {
          x: touch.clientX,
          y: touch.clientY,
          startX: this.position.x,
          startY: this.position.y
        }
        
        // 不立即开始拖拽，等待移动距离判断
        this.isDragging = false
        
        console.log('Drag start position:', this.dragStartPos)
        
        // 阻止事件冒泡，防止影响背景页面
        e.stopPropagation()
      }
    },
    
    // 触摸移动
    handleTouchMove(e) {
      if (this.isMobile && this.dragStartPos) {
        const touch = e.touches[0]
        const deltaX = touch.clientX - this.dragStartPos.x
        const deltaY = touch.clientY - this.dragStartPos.y
        const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY)
        
        // 移动距离超过10像素才开始拖拽
        if (!this.isDragging && distance > 10) {
          this.isDragging = true
          this.currentAnimation = 'excited'
        }
        
        // 如果正在拖拽，更新位置
        if (this.isDragging) {
          const screenWidth = this.systemInfo.windowWidth
          const screenHeight = this.systemInfo.windowHeight
          
          // 计算新位置
          let newX = this.dragStartPos.startX + (deltaX / screenWidth) * 100
          let newY = this.dragStartPos.startY + (deltaY / screenHeight) * 100
          
          // 边界限制
          newX = Math.max(5, Math.min(95, newX))
          newY = Math.max(5, Math.min(95, newY))
          
          // 更新位置
          this.position.x = newX
          this.position.y = newY
          
          // 阻止默认行为和事件冒泡
          e.preventDefault()
          e.stopPropagation()
        }
      }
    },
    
    // 触摸结束
    handleTouchEnd(e) {
      console.log('Touch end, isMobile:', this.isMobile, 'dragStartPos:', this.dragStartPos)
      
      if (this.isMobile && this.dragStartPos && e.changedTouches && e.changedTouches.length > 0) {
        const touch = e.changedTouches[0]
        const deltaX = touch.clientX - this.dragStartPos.x
        const deltaY = touch.clientY - this.dragStartPos.y
        const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY)
        
        console.log('Touch distance:', distance, 'isDragging:', this.isDragging)
        
        if (this.isDragging) {
          // 拖拽结束
          this.isDragging = false
          this.currentAnimation = 'happy'
          
          // 保存位置
          this.savePetPosition()
          
          setTimeout(() => {
            this.currentAnimation = 'idle'
          }, 1000)
          
          // 显示提示
          this.showBubbleMessage('我在这里！', 'normal')
        } else if (distance < 10) {
          // 短距离移动，认为是点击
          console.log('Detected click, showing menu')
          this.handlePetClick(e)
        }
        
        // 阻止事件冒泡
        e.stopPropagation()
        this.dragStartPos = null
      }
    },
    
    // 触摸取消
    handleTouchCancel(e) {
      if (this.isMobile) {
        this.isDragging = false
        this.dragStartPos = null
        this.currentAnimation = 'idle'
        
        // 阻止事件冒泡
        e.stopPropagation()
      }
    },
    
    // PC端点击事件
    handlePCClick(e) {
      if (!this.isMobile) {
        // PC端直接显示信息面板
        this.showInfoPanel = !this.showInfoPanel
      }
    },
    
    // 移动端点击事件（在触摸结束时调用）
    handlePetClick(e) {
      console.log('handlePetClick called, current showCustomMenu:', this.showCustomMenu)
      // 移动端显示自定义菜单
      this.showCustomMenu = !this.showCustomMenu
      console.log('After toggle, showCustomMenu:', this.showCustomMenu)
    },
    
    
    // 选择菜单项
    selectMenuItem(action) {
      this.showCustomMenu = false // 关闭菜单
      
      switch (action) {
        case 'info':
          this.showMobileInfo()
          break
        case 'feed':
          this.feedPet()
          break
        case 'play':
          this.playWithPet()
          break
        case 'rest':
          this.restPet()
          break
        case 'voice':
          this.toggleSpeechRecognition()
          break
        case 'settings':
          this.openSettings()
          break
        case 'close':
          this.closePet()
          break
      }
    },
    
    // 关闭自定义菜单
    closeCustomMenu() {
      this.showCustomMenu = false
    },
    
    
    // 关闭信息面板
    closeInfoPanel() {
      this.showInfoPanel = false
    },
    
    // 显示气泡消息
    showBubbleMessage(text, type = 'normal') {
      this.bubbleText = text
      this.bubbleType = type
      this.showBubble = true
      
      // 清除之前的定时器
      if (this.bubbleTimer) {
        clearTimeout(this.bubbleTimer)
      }
      
      // 3秒后自动隐藏
      this.bubbleTimer = setTimeout(() => {
        this.showBubble = false
        this.bubbleText = ''
      }, 3000)
    },
    
    // 开始随机动画
    startRandomAnimations() {
      const animations = ['idle', 'happy', 'excited']
      const randomAnimation = () => {
        if (!this.isDragging && !this.isInteracting) {
          this.currentAnimation = animations[Math.floor(Math.random() * animations.length)]
        }
        this.animationTimer = setTimeout(randomAnimation, 3000 + Math.random() * 5000)
      }
      randomAnimation()
    },
    
    // 开始状态更新
    startStatusUpdate() {
      this.statusUpdateTimer = setInterval(() => {
        this.updatePetStatus()
      }, 30000) // 每30秒更新一次
    },
    
    // 显示欢迎消息
    showWelcomeMessage() {
      setTimeout(() => {
        this.showBubbleMessage('你好！我是你的桌面宠物', 'happy')
      }, 1000)
    },
    
    // 移动端信息显示
    showMobileInfo() {
      this.showMobileInfoPanel = true
    },
    
    // 关闭移动端信息面板
    closeMobileInfoPanel() {
      this.showMobileInfoPanel = false
    },
    
    // 打开设置
    openSettings() {
      // 显示设置提示
      this.showBubbleMessage('设置功能开发中...', 'normal')
      // 这里可以添加具体的设置功能
      console.log('打开设置')
    },
    
    // 关闭宠物
    closePet() {
      this.showBubbleMessage('再见！', 'normal')
      setTimeout(() => {
        this.isVisible = false
        this.$emit('close-pet')
      }, 1000)
    },
    
    // 喂食宠物
    feedPet() {
      if (this.petData.hunger < 100) {
        this.petData.hunger = Math.min(100, this.petData.hunger + 30)
        this.petData.mood = Math.min(100, this.petData.mood + 10)
        this.currentAnimation = 'happy'
        this.showBubbleMessage('谢谢你的食物！', 'happy')
        this.savePetData()
        
        setTimeout(() => {
          this.currentAnimation = 'idle'
        }, 2000)
      } else {
        this.showBubbleMessage('我已经吃饱了！', 'normal')
      }
    },
    
    // 与宠物玩耍
    playWithPet() {
      if (this.petData.energy >= 10) {
        this.petData.energy = Math.max(0, this.petData.energy - 20)
        this.petData.mood = Math.min(100, this.petData.mood + 20)
        this.currentAnimation = 'excited'
        this.showBubbleMessage('太好玩了！', 'happy')
        this.savePetData()
        
        setTimeout(() => {
          this.currentAnimation = 'idle'
        }, 2000)
      } else {
        this.showBubbleMessage('我太累了，需要休息...', 'tired')
      }
    },
    
    // 让宠物休息
    restPet() {
      if (this.petData.energy < 100) {
        this.petData.energy = Math.min(100, this.petData.energy + 40)
        this.currentAnimation = 'idle'
        this.showBubbleMessage('休息一下...', 'normal')
        this.savePetData()
      } else {
        this.showBubbleMessage('我已经休息够了！', 'normal')
      }
    },
    
    // 更新宠物状态
    updatePetStatus() {
      // 饥饿度随时间减少
      this.petData.hunger = Math.max(0, this.petData.hunger - 2)
      
      // 精力随时间恢复
      this.petData.energy = Math.min(100, this.petData.energy + 1)
      
      // 心情根据其他状态调整
      if (this.petData.hunger < 20) {
        this.petData.mood = Math.max(0, this.petData.mood - 5)
      }
      
      if (this.petData.energy < 15) {
        this.petData.mood = Math.max(0, this.petData.mood - 3)
      }
      
      this.savePetData()
      this.checkPetStatus()
    },
    
    // 检查宠物状态
    checkPetStatus(petData = this.petData) {
      if (petData.hunger < 20) {
        this.showBubbleMessage('我饿了...', 'hungry')
      } else if (petData.energy < 15) {
        this.showBubbleMessage('我好累...', 'tired')
      } else if (petData.mood < 30) {
        this.showBubbleMessage('我不开心...', 'sad')
      }
    },
    
    // 保存宠物数据
    savePetData() {
      try {
        uni.setStorageSync('desktop_pet_data', this.petData)
        this.$emit('pet-data-updated', this.petData)
      } catch (error) {
        console.log('保存宠物数据失败:', error)
      }
    },
    
    // 设置语音识别
    setupSpeechRecognition() {
      // 使用语音识别管理器
      if (speechRecognitionManager.isRecognitionSupported()) {
        // 监听识别结果
        speechRecognitionManager.on('recognition-result', (result) => {
          this.handleVoiceCommand(result.command)
        })
        
        // 监听识别错误
        speechRecognitionManager.on('recognition-error', (error) => {
          console.log('语音识别错误:', error.error)
          this.showBubbleMessage('我听不清楚...', 'confused')
        })
        
        // 监听识别开始
        speechRecognitionManager.on('recognition-start', () => {
          this.showBubbleMessage('我在听...', 'listening')
        })
        
        // 监听识别结束
        speechRecognitionManager.on('recognition-end', () => {
          this.recognitionActive = false
          this.isListening = false
        })
      } else {
        console.warn('语音识别不支持')
      }
    },
    
    // 切换语音识别
    toggleSpeechRecognition() {
      if (!speechRecognitionManager.isRecognitionSupported()) {
        this.showBubbleMessage('抱歉，不支持语音识别', 'sad')
        return
      }
      
      if (this.recognitionActive) {
        speechRecognitionManager.stopListening()
        this.recognitionActive = false
        this.isListening = false
        this.showBubbleMessage('语音识别已关闭', 'normal')
      } else {
        const success = speechRecognitionManager.startListening()
        if (success) {
          this.recognitionActive = true
          this.isListening = true
        } else {
          this.showBubbleMessage('启动语音识别失败', 'sad')
        }
      }
    },
    
    // 处理语音命令
    handleVoiceCommand(command) {
      this.recognitionActive = false
      this.isListening = false
      
      if (!command || command.action === 'unknown') {
        this.showBubbleMessage('我听不懂，请再说一遍', 'confused')
        return
      }
      
      switch (command.action) {
        case 'feed':
          this.feedPet()
          break
        case 'play':
          this.playWithPet()
          break
        case 'rest':
          this.restPet()
          break
        case 'status':
          this.showMobileInfo()
          break
        default:
          this.showBubbleMessage('我听到了，但不知道怎么做', 'confused')
      }
    },
    
    // 检测Canvas支持
    checkCanvasSupport() {
      try {
        // 尝试创建Canvas上下文
        const testCanvasId = 'test_canvas_' + Date.now()
        const testCtx = uni.createCanvasContext(testCanvasId, this)
        
        if (!testCtx) {
          console.warn('Canvas not supported, using fallback mode')
          this.useFallback = true
        } else {
          console.log('Canvas supported, using Canvas renderer')
        }
      } catch (error) {
        console.error('Canvas check failed:', error)
        this.useFallback = true
      }
    },
    
    // Canvas准备就绪
    handleCanvasReady() {
      console.log('Canvas renderer ready')
    },
    
    // Canvas错误处理
    handleCanvasError(error) {
      console.error('Canvas error:', error)
      this.useFallback = true
      
      uni.showToast({
        title: '使用简化渲染模式',
        icon: 'none',
        duration: 2000
      })
    },
    
    // 清理资源
    cleanup() {
      if (this.bubbleTimer) {
        clearTimeout(this.bubbleTimer)
        this.bubbleTimer = null
      }
      
      if (this.animationTimer) {
        clearTimeout(this.animationTimer)
        this.animationTimer = null
      }
      
      if (this.statusUpdateTimer) {
        clearInterval(this.statusUpdateTimer)
        this.statusUpdateTimer = null
      }
      
      if (this.speechRecognition) {
        this.speechRecognition.stop()
        this.speechRecognition = null
      }
    }
  }
}
</script>

<style scoped>
/* 全局重置样式 */
.desktop-pet * {
  background-color: transparent !important;
  border: none !important;
  box-shadow: none !important;
}

.desktop-pet {
  position: fixed;
  z-index: 999999;
  cursor: pointer;
  user-select: none;
  pointer-events: auto;
  /* 确保宠物组件独立于页面滚动 */
  isolation: isolate;
  contain: layout style paint;
  /* 彻底移除所有背景和边框 */
  background: transparent !important;
  background-color: transparent !important;
  border: none !important;
  box-shadow: none !important;
  /* 移除所有可能的背景色 */
  outline: none !important;
  /* 添加悬浮效果 */
  filter: drop-shadow(0 4rpx 8rpx rgba(0, 0, 0, 0.1));
}

/* 确保宠物主体也是透明的 */
.desktop-pet > * {
  background: transparent !important;
  background-color: transparent !important;
  border: none !important;
  box-shadow: none !important;
}

/* PC端样式 */
.pet-pc {
  width: 100rpx;
  height: 100rpx;
}

/* 移动端样式 */
.pet-mobile {
  width: 100rpx;
  height: 100rpx;
}

/* 跟随状态 */
.pet-following {
  cursor: grabbing;
}

/* 交互状态 */
.pet-interacting {
  pointer-events: none;
}


/* 响应式调整 */
@media screen and (max-width: 750rpx) {
  .pet-mobile {
    width: 90rpx;
    height: 90rpx;
  }
}
</style>